package com.ruoyi.energy.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.energy.domain.QyEnterprise;
import com.ruoyi.energy.domain.vo.NyMeterAccountExcelVO;
import com.ruoyi.energy.domain.vo.NyMeterAccountVO;
import com.ruoyi.energy.mapper.NyMeterAccountMapper;
import com.ruoyi.energy.service.INyMeterAccountService;
import com.ruoyi.energy.service.INyMeterManagementService;
import com.ruoyi.energy.service.IQyEnterpriseService;
import com.ruoyi.energy.service.manager.NyMeterAccountManager;
import com.ruoyi.omp.api.domain.NyMeterAccount;
import com.ruoyi.system.api.RemoteBmCodeService;
import com.ruoyi.system.api.domain.RemoteSysBmType;
import com.ruoyi.system.api.enums.SysBmCodeTypeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仪表台账Service业务层处理
 *
 * @author cjie
 * @date 2021-07-29
 */
@Service
public class NyMeterAccountServiceImpl implements INyMeterAccountService {
    @Autowired
    private NyMeterAccountMapper nyMeterAccountMapper;

    @Autowired
    private INyMeterManagementService nyMeterManagementService;

    @Autowired
    private RemoteBmCodeService remoteBmCodeService;

    @Autowired
    private IQyEnterpriseService qyEnterpriseService;

    @Autowired
    private NyMeterAccountManager nyMeterAccountManager;

    /**
     * 查询仪表台账
     *
     * @param id 仪表台账ID
     * @return 仪表台账
     */
    @Override
    public NyMeterAccount selectNyMeterAccountById(String id) {
        return nyMeterAccountMapper.selectNyMeterAccountById(id);
    }

    /**
     * 查询仪表台账列表
     *
     * @param nyMeterAccount 仪表台账
     * @return 仪表台账
     */
    @Override
    public List<NyMeterAccount> selectNyMeterAccountList(NyMeterAccount nyMeterAccount) {
        return nyMeterAccountMapper.selectNyMeterAccountList(nyMeterAccount);
    }

    //查询总表下的私表
    @Override
    public List<NyMeterAccount> selectPrivateNyMeterList(NyMeterAccount nyMeterAccount) {
        NyMeterAccount search = new NyMeterAccount();
        search.setParentId(nyMeterAccount.getId());
        List<NyMeterAccount> nyMeterAccounts = nyMeterAccountMapper.selectNyMeterAccountList(search);
        //查询考核表下的私表
        if(nyMeterAccounts.size()>0){
            List<String> assessIds = nyMeterAccounts.stream().map(NyMeterAccount::getId).collect(Collectors.toList());
            List<NyMeterAccount> privates = nyMeterAccountMapper.selectNyMeterAccountListByParentIds(assessIds);
            return privates;
        }
        return null;
    }

    /**
     * 新增仪表台账，同时增加仪表配置
     *
     * @param nyMeterAccount 仪表台账
     * @return 结果
     */
    @Override
    public int insertNyMeterAccount(NyMeterAccount nyMeterAccount) {
        nyMeterAccount.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        nyMeterAccount.setCreateTime(DateUtils.getNowDate());
        nyMeterAccount.setCreateBy(SecurityUtils.getUsername());
        if(nyMeterAccount.getShareInitialValue() != null){
            if(nyMeterAccount.getShareInitialValue().compareTo(BigDecimal.ZERO)<0){
                nyMeterAccount.setShareInitialValue(BigDecimal.ZERO);
            }
        }
        int result = nyMeterAccountMapper.insertNyMeterAccount1(nyMeterAccount);
        nyMeterAccountMapper.insertNyMeterAccount2(nyMeterAccount);
//        if(result>0){
//            NyMeterManagement management = new NyMeterManagement();
//            management.setMeterId(nyMeterAccount.getId());
//            nyMeterManagementService.insertNyMeterManagement(management);
//        }
        return result;
    }

    /**
     * 修改仪表台账
     *
     * @param nyMeterAccount 仪表台账
     * @return 结果
     */
    @Override
    public int updateNyMeterAccount(NyMeterAccount nyMeterAccount) {
        nyMeterAccount.setUpdateTime(DateUtils.getNowDate());
        nyMeterAccount.setUpdateBy(SecurityUtils.getUsername());
        if(nyMeterAccount.getShareInitialValue() != null){
            if(nyMeterAccount.getShareInitialValue().compareTo(BigDecimal.ZERO)<0){
                nyMeterAccount.setShareInitialValue(BigDecimal.ZERO);
            }
        }
        int result = nyMeterAccountMapper.updateNyMeterAccount1(nyMeterAccount);
        nyMeterAccountMapper.updateNyMeterAccount2(nyMeterAccount);
        return result;
    }

    /**
     * 批量删除仪表台账
     *
     * @param ids 需要删除的仪表台账ID
     * @return 结果
     */
    @Override
    public int deleteNyMeterAccountByIds(String[] ids) {
        return nyMeterAccountMapper.deleteNyMeterAccountByIds(ids);
    }

    /**
     * 删除仪表台账信息
     *
     * @param id 仪表台账ID
     * @return 结果
     */
    @Override
    public int deleteNyMeterAccountById(String id) {
        return nyMeterAccountMapper.deleteNyMeterAccountById(id);
    }

/*    @Override
    public NyMeterAccountVO selectRoot(String id) {
        NyMeterAccountVO result = nyMeterAccountMapper.selectRoot(id);
        if(result == null){
            return result;
        }
        if(result.getChildren().size() == 0){
            return result;
        }
        for(Iterator<NyMeterAccountVO> iterator = result.getChildren().iterator(); iterator.hasNext();){
            NyMeterAccountVO nyMeterAccountVO = (NyMeterAccountVO) iterator.next();
            if(nyMeterAccountVO.getCategory().equals("考核表")){
                NyMeterAccountVO result1 = selectRoot(nyMeterAccountVO.getId());
                if(result1.getChildren().size() == 0){
                    continue;
                }
                nyMeterAccountVO = result1;
            }
        }
        return result;
    }*/

    //@Override


    @Override
    public String importData(List<NyMeterAccountExcelVO> nyCableVOList,String meterType) {
        if (StringUtils.isNull(nyCableVOList) || nyCableVOList.size() == 0) {
            throw new CustomException("导入抄表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        nyCableVOList = nyCableVOList.stream().filter(o->StringUtils.isNotBlank(o.getInstallPositionS())).collect(Collectors.toList());
        this.insertDataBatch(nyCableVOList,meterType);
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + nyCableVOList.size() + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public NyMeterAccountVO selectRoot(String id) {
        return nyMeterAccountManager.selectRoot(id);
    }

    private void insertDataBatch(List<NyMeterAccountExcelVO> nyCableVOList,String meterType){
        //批量插入数据
        //List<NyMeterAccountExcelVO> sysBmTypeExcelVOS = nyCableVOList.stream().filter(o -> StringUtils.isNotBlank(o.getMeterName())).collect(Collectors.toList());

        Map<String, List<NyMeterAccountExcelVO>> listMap = nyCableVOList.stream().collect(Collectors.groupingBy(NyMeterAccountExcelVO::getMeterName));

        for (Map.Entry<String, List<NyMeterAccountExcelVO>> entry : listMap.entrySet()) {
            String meterName = entry.getKey();

            NyMeterAccount account = new NyMeterAccount();
            account.setMeterType(meterType);
            account.setCategory("0");
            account.setMeterName(meterName);
            NyMeterAccountExcelVO accountExcelVO = entry.getValue().get(0);
            account.setParkNum(accountExcelVO.getParkNum());
            List<NyMeterAccount> res = nyMeterAccountMapper.selectNyMeterAccountList(account);
            //zongbiao not exsit,插入 0
            if(res.size()==0){
                RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(accountExcelVO.getMeterNum(), SysBmCodeTypeValue.DEVICE);
                account.setMeterNum(bmType.getNowCode());
                account.setMeterName(accountExcelVO.getMeterName());
                //account.setStandard(accountExcelVO.getStandard());
                if(accountExcelVO.getMagnification() != null){
                    account.setMagnification(accountExcelVO.getMagnification());
                }else {
                    account.setMagnification(BigDecimal.ONE);
                }

                account.setInitialValue(accountExcelVO.getInitialValue());
                account.setCurrentValue(accountExcelVO.getCurrentValue());
                account.setShareInitialValue(accountExcelVO.getShareInitialValue());
                account.setBuildingNum(accountExcelVO.getBuildingNum());
                //account.setMeterCode(accountExcelVO.getMeterCode());
                account.setInstallPosition(accountExcelVO.getInstallPosition());
                account.setMeterType(meterType);
                account.setMeterModel(accountExcelVO.getMeterModel());
                this.insertNyMeterAccount(account);
            }

            Map<String, List<NyMeterAccountExcelVO>> listMap1 = entry.getValue().stream().collect(Collectors.groupingBy(NyMeterAccountExcelVO::getMeterModelKH));
            for(Map.Entry<String, List<NyMeterAccountExcelVO>> entry1 : listMap1.entrySet()){
                String meterNameKH = entry1.getKey();

                NyMeterAccount accountKH = new NyMeterAccount();
                accountKH.setMeterType(meterType);
                NyMeterAccountExcelVO accountExcelVO1 = entry1.getValue().get(0);
                accountKH.setParkNum(accountExcelVO1.getParkNum());
                accountKH.setInitialValue(accountExcelVO1.getInitialValueKH());
                accountKH.setCurrentValue(accountExcelVO1.getCurrentValueKH());
                accountKH.setMeterModel(accountExcelVO1.getMeterModelKH());
                List<NyMeterAccount> res1 = nyMeterAccountMapper.selectNyMeterAccountList(accountKH);
                if(res1.size()==0 && StringUtils.isNotBlank(accountExcelVO1.getMeterModelKH())){
                    RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(accountExcelVO1.getMeterNum(), SysBmCodeTypeValue.DEVICE);
                    accountKH.setMeterNum(bmType.getNowCode());
                    accountKH.setMeterName(accountExcelVO1.getMeterNameKH());
                    accountKH.setCategory("1");
                    //account.setStandard(accountExcelVO.getStandard());
                    if(accountExcelVO1.getMagnificationKH() != null){
                        accountKH.setMagnification(accountExcelVO1.getMagnificationKH());
                    }else {
                        accountKH.setMagnification(BigDecimal.ONE);
                    }
                    accountKH.setBuildingNum(accountExcelVO1.getBuildingNumKH());
                    accountKH.setInstallPosition(accountExcelVO1.getInstallPositionKH());
                    accountKH.setMeterType(meterType);
                    accountKH.setParentId(account.getId());
                    this.insertNyMeterAccount(accountKH);
                }else {
                    accountKH = res1.get(0);
                    if(accountKH.getCategory().equals("2")){
                        accountKH.setCategory("1");
                        this.updateNyMeterAccount(accountKH);
                    }
                }
                Map<String, List<NyMeterAccountExcelVO>> listMap2 = entry1.getValue().stream().collect(Collectors.groupingBy(NyMeterAccountExcelVO::getMeterModelS));

                for(Map.Entry<String, List<NyMeterAccountExcelVO>> entry2 : listMap2.entrySet()) {
                    String meterNameS = entry2.getKey();

                    NyMeterAccount accountS = new NyMeterAccount();
                    accountS.setMeterType(meterType);
                    accountS.setCategory("2");
                    accountS.setMeterModel(meterNameS);
                    NyMeterAccountExcelVO accountExcelVO12 = entry2.getValue().get(0);
                    accountS.setParkNum(accountExcelVO12.getParkNum());
                    List<NyMeterAccount> res2 = nyMeterAccountMapper.selectNyMeterAccountList(accountS);
                    if (res2.size() == 0) {
                        RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(accountExcelVO12.getMeterNum(), SysBmCodeTypeValue.DEVICE);
                        accountS.setMeterNum(bmType.getNowCode());
                        accountS.setMeterName(accountExcelVO12.getMeterNameS());
                        //account.setStandard(accountExcelVO.getStandard());
                        if(accountExcelVO12.getMagnificationS() != null){
                            accountS.setMagnification(accountExcelVO12.getMagnificationS());
                        }else {
                            accountS.setMagnification(BigDecimal.ONE);
                        }

                        accountS.setInitialValue(accountExcelVO12.getInitialValueS());
                        accountS.setCurrentValue(accountExcelVO12.getCurrentValueS());
                        accountS.setBuildingNum(accountExcelVO12.getBuildingNumS());
                        accountS.setInstallPosition(accountExcelVO12.getInstallPositionS());
                        accountS.setMeterModel(accountExcelVO12.getMeterModelS());
                        if(StringUtils.isNotBlank(accountExcelVO12.getMeterModelKH())){
                            accountS.setParentId(accountKH.getId());
                        }else {
                            accountS.setParentId(account.getId());
                        }
                        QyEnterprise qy = queryQyEnterpriseByName(accountExcelVO12.getEnterpriseName());
                        if(qy !=null){
                            accountS.setEnterpriseName(qy.getEnterpriseName());
                            accountS.setEnterpriseId(qy.getId());
                        }else {
                            accountS.setEnterpriseName(accountExcelVO12.getEnterpriseName());
                        }
                        accountS.setRemark(accountExcelVO12.getRemark());
                        accountS.setUse1(accountExcelVO12.getUse1());
                        this.insertNyMeterAccount(accountS);
                    }
                }

            }

        }

    }

    private QyEnterprise queryQyEnterpriseByName(String name){
        QyEnterprise qyEnterprise = new QyEnterprise();
        qyEnterprise.setEnterpriseName(name);
        List<QyEnterprise> res = qyEnterpriseService.selectQyEnterpriseList(qyEnterprise);
        if(res.size()==0){
            return null;
        }
        return res.get(0);
    }

}
